package searcher;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import org.apache.lucene.document.Document;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.TopDocs;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.SimpleFSDirectory;
import org.wltea.analyzer.lucene.IKQueryParser;
import org.wltea.analyzer.lucene.IKSimilarity;

import bean.Grass;

public class Searcher {
	private final String INDEXPATH = "index";

	public List<Grass> search(String key) {
		try {
			List<Grass> list=new ArrayList<Grass>();
			Directory directory = new SimpleFSDirectory(new File(this.getClass().getResource("/").getPath()+"/index"));
			IndexSearcher is = new IndexSearcher(directory);
			is.setSimilarity(new IKSimilarity());

			Query query = IKQueryParser.parse("text", key);
			TopDocs th = is.search(query, 10);

			ScoreDoc[] sd = th.scoreDocs;
			for (int i = 0; i < sd.length; i++) {
				ScoreDoc s = sd[i];
				Document doc = is.doc(s.doc);
				Grass grass=new Grass();
				grass.setText(doc.get("text"));
				grass.setId(doc.get("id"));
				list.add(grass);

			}
			return list;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}
}
